$(document).ready(
		function() {
			session = new Session();
			error = new Error();
			tracks = new Tracks();
			file = {};

			function clearMain() {
				$("#listViewTrackPoints").children().remove();
				$("#labelViewTrackName").html("");
				$("#labelViewTrackLocation").html("");
				$("#panelViewTrackPoints").slideUp('fast');
				$("#panelViewPoint").slideUp('fast');
			}

			function updateTrackList() {
				$("#listTracks").children().remove();
				for ( var i in tracks.list) {
					$("#listTracks").append(
							$("<li></li>").html(tracks.list[i].name).val(
									tracks.list[i].id).click(function() {
								selectTrack(this);
							}));
				}
			}

			function selectTrack(trackObj) {
				$(trackObj).parent().children().removeClass("selected");
				$(trackObj).addClass("selected");
				$("#panelViewTrackPoints").show();

				tracks.select($(trackObj).val());
				$("#panelViewPoint").slideUp('fast');

				$("#labelViewTrackName").html(tracks.active.name);
				$("#labelViewTrackLocation").html(tracks.active.location);

				updatePointsList();
			}

			function updatePointsList() {
				$("#listViewTrackPoints").children().remove();
				for ( var i = 0; i < tracks.active.points.length; i++) {
					var lat = tracks.active.points[i].latitude
							+ (tracks.active.points[i].north == "true" ? "N"
									: "S");

					var lon = tracks.active.points[i].longitude
							+ (tracks.active.points[i].west == "true" ? "W"
									: "E");

					$("#listViewTrackPoints").append(
							$("<li></li>").html(lat + ", " + lon).val(i).click(
									function() {
										selectPoint(this);
									}));
				}
			}

			function selectPoint(pointObj) {
				var index = $(pointObj).val();

				var lat = tracks.active.points[index].latitude
						+ (tracks.active.points[index].north == "true" ? "N"
								: "S");

				var lon = tracks.active.points[index].longitude
						+ (tracks.active.points[index].west == "true" ? "W"
								: "E");
				
				var img = tracks.active.id + "_" + index + ".jpg";

				$("#lablePointLat").html(lat);
				$("#lablePointLon").html(lon);
				file.remoteName = img;
				
				$("#panelViewPoint").slideDown('fast', function() {
					if (tracks.active.points[index].image) {
						$("#imgPointImage").attr("src", "/img/" + img);
						$("#imgPointImage").slideDown('fast');
					}
				});
			}

			function showLogin(callback) {
				if ($("#panelTrack").is(":visible")) {
					$("#panelTrack").slideUp('fast', function() {
						$("#panelLogin").slideDown('fast', callback);
					});
				} else if ($("#panelNavWorking").is(":visible")) {
					$("#panelNavWorking").slideUp('fast', function() {
						$("#panelLogin").slideDown('fast', callback);
					});
				} else {
					$("#panelLogin").slideDown('fast', callback);
				}
			}

			function showTracks(callback) {
				if ($("#panelLogin").is(":visible")) {
					$("#panelLogin").slideUp('fast', function() {
						$("#panelTrack").slideDown('fast', callback);
					});
				} else if ($("#panelNavWorking").is(":visible")) {
					$("#panelNavWorking").slideUp('fast', function() {
						$("#panelTrack").slideDown('fast', callback);
					});
				} else {
					$("#panelTrack").slideDown('fast', callback);
				}
			}

			function showNavWorking(callback) {
				if ($("#panelLogin").is(":visible")) {
					$("#panelLogin").slideUp('fast', function() {
						$("#panelNavWorking").slideDown('fast', callback);
					});
				} else if ($("#panelTrack").is(":visible")) {
					$("#panelTrack").slideUp('fast', function() {
						$("#panelNavWorking").slideDown('fast', callback);
					});
				} else {
					$("#panelNavWorking").slideDown('fast', callback);
				}
			}

			// Show Add Track
			$("#btnShowAddTrack").click(function() {
				$("#panelAddTrack").slideToggle('fast');
			});

			// Add Track
			$("#btnAddTrack").click(
					function() {
						addTrack($("#txtAddTrackName").val(), $(
								"#txtAddTrackLocation").val(),
								function(success) {
									if (success) {
										updateTrackList();
										$("#panelAddTrack").slideUp(
												'fast',
												function() {
													$("#txtAddTrackName").val(
															"");
													$("#txtAddTrackLocation")
															.val("");
												});
									} else {
										$("#labelAddTrackMessage").html(
												error.message);
									}
								});
					});

			// Show Add Point
			$("#btnShowAddPoint").click(function() {
				$("#panelAddPoint").slideToggle('fast');
			});

			$("#btnAddPoint").click(function() {
				var point = {
					latitude : $("#txtAddPointLat").val(),
					north : $("#txtAddPointLatN").val(),
					longitude : $("#txtAddPointLon").val(),
					west : $("#txtAddPointLonW").val(),
					image : false
				};

				if (Array.isArray(tracks.active.points)) {
					tracks.active.points.push(point);
				} else {
					tracks.active.points = new Array(point);
				}

				updateTrack(tracks.active.id, function(success) {
					if (success) {
						$("#panelAddPoint").slideUp('fast');
						$("#labelAddPointMessage").html("");
						updatePointsList();
					} else {
						$("#labelAddPointMessage").html(error.message);
					}
				});
			})
			
			$("#btnUploadPointImage").click(function() {
				upload($("#filePointImage")[0].files[0], file.remoteName, function(success) {
					if(success) {
						alert("Good!");
					} else {
						$("#labelUploadMessage").html(error.message);
					}
				});
			})

			// Login
			$("#btnLogin").click(
					function() {
						showNavWorking(function() {
							login($("#txtLoginName").val(), $(
									"#txtLoginPassword").val(),
									function(success) {
										if (success) {
											$("#labelLoginMessage").html("");
											$("#labelUser").html(
													session.user.name);
											getTracks(function() {
												updateTrackList();
												showTracks();
											});
										} else {
											$("#labelLoginMessage").html(
													error.message);
											showLogin();
										}

										$("#txtLoginName").val("");
										$("#txtLoginPassword").val("");
									});
						});
					});

			// Logout
			$("#btnLogout").click(function() {
				showNavWorking(function() {
					logout(function(success) {
						if (success) {
							$("#labelUserMessage").html("");
							clearMain();
							showLogin();
						} else {
							$("#labelLoginMessage").html(error.message);
							showLogin();
						}
					});
				});
			});

			// Cookie
			if (session.getCookie()) {
				var req = session.command('getSession');
				doPost(req, function(res) {
					if (res.success) {
						$("#labelLoginMessage").html("");
						session.set(res.session);
						session.setCookie(); // Update
						// expiration
						// time on
						// reload

						$("#labelUser").html(session.user.name);
						getTracks(function() {
							updateTrackList();
							showTracks();
						});
					} else {
						$("#labelLoginMessage").html(res.error.message);
						showLogin();
					}
				});
			} else {
				showLogin();
			}
		});